# -*- coding: utf-8 -*-
"""
Created on Sun Dec 19 15:26:27 2021

@author: wulong
"""
import numpy as np
from casadi import *
from Long_term_model import* 

# In[1] Long-term MPC
def formulate_opt_l(initial_state, state_guess, state_bnds_lo, state_bnds_up, 
                    input_cont_guess, input_cont_bnds_lo, input_cont_bnds_up, 
                    input_cont_lbg, input_cont_ubg, 
                    input_bin_guess, input_bin_bnds_lo, input_bin_bnds_up, 
                    distb_bnds,
                    output_guess, 
                    output_setpnts, output_setpnts_lo, output_setpnts_up, 
                    alpha, alpha_slack, pred_horzn):
    w = []
    w0 = []
    lbw = []
    ubw = []
    discrete = []
    J = 0
    g = []
    lbg = []
    ubg = []
    
    # "Lift" initial states conditions
    xname = 'X' + str(0)
    Xk = MX.sym(xname, Nx_l)
    w += [Xk]
    lbw += [initial_state]
    ubw += [initial_state]
    w0 += [initial_state]
    discrete += [False]*Nx_l
    
    for k in range(1, pred_horzn+1):
        # Create input variables
        uname = 'U' + str(k-1)
        Uk = MX.sym(uname, Nuc_l)
        w += [Uk]
        lbw +=[input_cont_bnds_lo]
        ubw +=[input_cont_bnds_up]
        w0 += [input_cont_guess]
        discrete += [False]*Nuc_l
        
        zname = 'Z' + str(k-1)
        Zk = MX.sym(zname, Nuz_l)
        w += [Zk]
        lbw +=[input_bin_bnds_lo]
        ubw +=[input_bin_bnds_up]
        w0 += [input_bin_guess]
        discrete += [True]*Nuz_l
        
        # Add input constraints
        Zu = vertcat(Zk[0], Zk[1], Zk[2], 1, 1)
        g += [Uk - Zu*input_cont_lbg]
        g += [Zu*input_cont_ubg - Uk]
        lbg += [[0]*Nuc_l*2]
        ubg += [[np.inf]*Nuc_l*2]
        
        # Create disturbance
        # Index k-1 represents disturbance prediction at k in disturbance sequence,
        # because of python starting from 0.
        Dk = distb_bnds[k-1,:]
        
        # Simulate the model
        Ik = I_ode_l(x0 = Xk, p = vertcat(Uk, Zk, Dk))
        X_int = Ik['xf']
        
        # Create new states variables
        xname = 'X' + str(k)
        Xk = MX.sym(xname, Nx_l)
        w += [Xk]
        lbw += [state_bnds_lo]
        ubw += [state_bnds_up]
        w0 += [state_guess]
        discrete += [False]*Nx_l
        
        # Add dynamic constraints
        g += [X_int - Xk]
        lbg += [[0]*Nx_l]
        ubg += [[0]*Nx_l]
        
        # Create outputs variables
        yname = 'y' + str(k)
        Yk = MX.sym(yname, Ny_l)
        w += [Yk]
        lbw += [[-np.inf]*Ny_l] 
        ubw += [[np.inf]*Ny_l]
        w0 += [output_guess]
        discrete += [False]*Ny_l
        
        # Add output constraints
        g += [Yk - out_ies_l(Xk, Uk, Zk, Dk)]
        lbg += [[0]*Ny_l]
        ubg += [[0]*Ny_l]
        
        # Add slack variables
        ename = 'e' + str(k)
        ek = MX.sym(ename, 3)
        w += [ek]
        lbw += [[0]*3] 
        ubw += [[np.inf]*3]
        w0 += [[0]*3]
        discrete += [False]*3    
        
        # Add target constraints
        g += [Yk[0] - output_setpnts[k-1] + ek[0]]
        lbg += [[0]]
        ubg += [[0]]
        
        g += [Yk[1] + ek[1] - ek[2]]
        lbg += [output_setpnts_lo[k-1]]
        ubg += [output_setpnts_up[k-1]]
        
        # The cost function
        J += alpha*(Uk[0] + Uk[1])
        J += alpha_slack[0]*ek[0]**2
        J += alpha_slack[1]*ek[1]**2
        J += alpha_slack[2]*ek[2]**2
        
        pass
    
    # Concatenate decision variables and constraint terms
    w = vertcat(*w)
    lbw = vertcat(*lbw)
    ubw = vertcat(*ubw)
    w0 = vertcat(*w0)
    g = vertcat(*g)
    lbg = vertcat(*lbg)
    ubg = vertcat(*ubg)
    
    return w, lbw, ubw, w0, g, lbg, ubg, discrete, J

# In[2] Creat Long-term MPC solver
def solve_opt_l(w, lbw, ubw, w0, g, lbg, ubg, discrete, J):
    print('Creat an L-MPC solver')
    nlp_prob = {'f': J, 'x': w, 'g': g}
    nlp_solver = nlpsol('nlp_solver', 'bonmin', nlp_prob, {"discrete": discrete})
    # Solve NLP
    print('Solve L-MPC')
    # nlp_solver.stats()
    sol = nlp_solver(x0=w0, lbx=lbw, ubx=ubw, lbg=lbg, ubg=ubg)
    print(nlp_solver.stats())
    optimalValues = sol['x'].full().ravel()
    
    return optimalValues